package cn.zhqr.common.util.number;

import java.util.Random;

/**
 * 随机字符生成器
 */
public final class RandomUtils {
    public RandomUtils() {}

    /**
     * 生成随机数字串
     * @param length
     * @return
     */
    public static String randomNumberStr(int length) {
        return randomStr(length, CharType.NUMBER);
    }


    public static String randomStr(int length, CharType type) {
        String randomCode = "";
        String strTable = type == CharType.NUMBER ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;

        do {
            randomCode = "";
            int count = 0;

            for(int i = 0; i < length; ++i) {
                double dblR = Math.random() * (double)len;
                int intR = (int)Math.floor(dblR);
                char c = strTable.charAt(intR);
                if ('0' <= c && c <= '9') {
                    ++count;
                }

                randomCode = randomCode + strTable.charAt(intR);
            }

            if (count >= 2) {
                bDone = false;
            }
        } while(bDone);

        return randomCode.toUpperCase();
    }

    /**
     * 生成指定范围内的随机数
     * @param min
     * @param max
     * @return
     */
    public static int randomInt(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

    public enum CharType {
        NUMBER,
        LETTER_NUMBER;
    }
}
